"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
/**
 * Created by liuhe on 2016/11/30.
 */
('use strict');
//引入model
const mongoose = require("mongoose");
const global_setup_model_1 = require("../dao/globalSetup/global-setup-model");
const business_config_service_1 = require("./business-config-service");
const Immutable = require("immutable");
//默认数据
let defaultGlobalSetup = Immutable.fromJS({
    //站点设置 全局的,title seo icon
    siteTitle: '',
    siteIconImgSrc: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/editLeftNav/blank_icon.png',
    host: {
        pc: '',
        weixin: '',
        api_host: ''
    },
    platformInfo: {
        pc: {
            logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
        },
        weixin: {
            logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
        },
        app: {
            logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
        },
        pad: {
            logo: 'https://qianmi-web.oss-cn-hangzhou.aliyuncs.com/x-site/public/img/x-stie.png'
        }
    }
});
const defaultSiteTitle = {
    d2p: '我的订货',
    d2cStore: '我的商城',
    ehome: '我的家政'
};
class GlobalSetupService {
    /**
       * type 实例方法
       * 获取globalSetup 进入到编辑页 ，页面管理页面，选择模板页面需要获取全量globalSetup数据
       * @param uid         用户ID
       * @param systemCode  业务线标示
       * @returns {Promise}
       */
    static async getGlobalSetup({ uid, systemCode }) {
        let globalSetup = await GlobalSetupService.getGlobalSetupFromDB({ uid, systemCode });
        if (!globalSetup) {
            globalSetup = defaultGlobalSetup.toJS();
            globalSetup.uid = uid;
            globalSetup.systemCode = systemCode;
            globalSetup.siteTitle = defaultSiteTitle[systemCode] ? defaultSiteTitle[systemCode] : '我的站点';
            //将数据保存如数据库
            await GlobalSetupService.saveGlobalSetup2DB(globalSetup);
        }
        //数据兼容
        if (globalSetup && !globalSetup.platformInfo) {
            globalSetup.platformInfo = {};
        }
        return globalSetup;
    }
    static async getSiteId({ uid, systemCode }) {
        let id = await new Promise((resolve, reject) => {
            global_setup_model_1.default.findOne({ uid, systemCode }).select('_id').lean().exec((err, data) => {
                err ? reject(err) : resolve((data && data._id) || null);
            });
        });
        if (!id) {
            let globalSetup = defaultGlobalSetup.toJS();
            globalSetup.uid = uid;
            globalSetup.systemCode = systemCode;
            globalSetup.siteTitle = defaultSiteTitle[systemCode] ? defaultSiteTitle[systemCode] : '我的站点';
            //将数据保存如数据库
            id = await GlobalSetupService.saveGlobalSetup2DB(globalSetup);
            await business_config_service_1.default.initConfigInfo(id);
        }
        return id;
    }
    /**
       * 从数据库获取globalSetup
       * @param uid
       * @param systemCode
       * @returns {Promise}
       */
    static getGlobalSetupFromDB({ uid, systemCode }) {
        return new Promise((resolve, reject) => {
            global_setup_model_1.default.findOne({ uid, systemCode }).select('-sitemanager').lean().exec(function (err, data) {
                err ? reject(err) : resolve(data);
            });
        });
    }
    /**
       * 保存数据到数据库
       * @param globalSetup
       * @returns {Promise}
       */
    static saveGlobalSetup2DB(globalSetup) {
        return new Promise((resolve, reject) => {
            new global_setup_model_1.default(globalSetup).save((err, data) => {
                err ? reject(err) : resolve(data._id);
            });
        });
    }
    /**
       * 保存数据到数据库 有则改之 无则加之
       * @param globalSetup
       * @returns {Promise}
       */
    static upsertGlobalSetup(globalSetup) {
        let { uid, systemCode } = globalSetup;
        let target = { uid, systemCode };
        delete globalSetup._id;
        delete globalSetup.__v;
        return new Promise((resolve, reject) => {
            global_setup_model_1.default.update(target, globalSetup, {
                upsert: true
            }).exec(function (err, data) {
                err ? reject(err) : resolve(data);
            });
        });
    }
    /**
     * 获取globalSetup中的指定信息
     * eg  path = 'siteTitle siteIconImgSrc host.pc'  return {siteTitle:xx ,siteIconImgSrc:xx , host.pc:xx }
     * @param id
     * @param uid
     * @param systemCode
     * @param path
     * @returns {Promise<T>}
     */
    static getSiteInfo({ id, uid, systemCode, path }) {
        return new Promise((resolve, reject) => {
            let query = mongoose.Types.ObjectId.isValid(id)
                ? global_setup_model_1.default.findById(id)
                : global_setup_model_1.default.findOne({ uid, systemCode });
            query.select(path).lean().exec((err, data) => {
                if (err) {
                    reject(err);
                }
                else {
                    let result = {};
                    let siteInfo = Immutable.fromJS(data);
                    let targetArr = path.split(' ');
                    for (let i = 0, len = targetArr.length; i < len; i++) {
                        let target = targetArr[i];
                        let targetPath = target.split('.');
                        let targetValue = siteInfo.getIn(targetPath);
                        result[target] = targetValue && targetValue.toJS ? targetValue.toJS() : targetValue;
                    }
                    resolve(result);
                }
            });
        });
    }
    /**
       * 全量更新页面信息 发布页面的时候 包括用户icon和title的同步修改
       * @param id
       * @param uid
       * @param systemCode
       * @param siteInfo
       * @returns {Promise}
       */
    static updateSiteInfo({ id, uid, systemCode, siteInfo }) {
        return new Promise((resolve, reject) => {
            mongoose.Types.ObjectId.isValid(id)
                ? global_setup_model_1.default.findByIdAndUpdate(id, { $set: siteInfo }).exec((err, data) => {
                    err ? reject(err) : resolve(data);
                })
                : global_setup_model_1.default.findOneAndUpdate({ uid, systemCode }, { $set: siteInfo }).exec((err, data) => {
                    err ? reject(err) : resolve(data);
                });
        });
    }
    static async getUsersList({ systemCode, uid, pageNum, pageSize }) {
        pageNum = parseInt(pageNum, 10);
        pageSize = parseInt(pageSize, 10);
        let target = { systemCode };
        if (uid) {
            let uidArr = [];
            uid.split(',').forEach((curId, index) => {
                curId = curId.trim();
                if (curId) {
                    uidArr.push(curId);
                }
            });
            target.uid = { $in: uidArr };
        }
        let totalCount = await new Promise((resolve, reject) => {
            global_setup_model_1.default.count(target, function (err, data) {
                err ? reject(err) : resolve(data);
            });
        });
        let usersList = [];
        if (pageNum > 0) {
            let index = pageNum * pageSize;
            let item = await new Promise((resolve, reject) => {
                global_setup_model_1.default.aggregate([
                    { $match: target },
                    { $limit: index },
                    { $sort: { _id: -1 } },
                    { $limit: 1 }
                ]).exec(function (err, data) {
                    err ? reject(err) : resolve(data.length > 0 ? data[0] : null);
                });
            });
            let objectId = item && item._id;
            usersList = await new Promise((resolve, reject) => {
                target._id = { $gt: objectId };
                global_setup_model_1.default.find(target).select('-sitemanager').limit(pageSize).exec((err, data) => {
                    err ? reject(err) : resolve(data);
                });
            });
        }
        else {
            //第一页数据仍然用skip
            usersList = await new Promise((resolve, reject) => {
                global_setup_model_1.default.find(target)
                    .select('-sitemanager')
                    .skip(pageNum * pageSize)
                    .limit(pageSize)
                    .exec((err, data) => {
                    err ? reject(err) : resolve(data);
                });
            });
        }
        return { totalCount, usersList };
    }
    static getAllGlobalSetupCount({ systemCode, uid }) {
        let target = { systemCode };
        if (uid) {
            let uidArr = [];
            uid.split(',').forEach((curId, index) => {
                curId = curId.trim();
                if (curId) {
                    uidArr.push(curId);
                }
            });
            target.uid = { $in: uidArr };
        }
        return new Promise((resolve, reject) => {
            global_setup_model_1.default.count(target, function (err, data) {
                err ? reject(err) : resolve(data);
            });
        });
    }
}
exports.default = GlobalSetupService;
